'''
Created on Mar 9, 2010

@author: oabalbin
'''
import sys
import os
import glob
import signatures.db.tables as dt
import signatures.db.query as dq

import signatures.parsers.read_microarray_data as pm
from signatures.common.classes import drugBankrecord2
from collections import deque
from collections import defaultdict


class drugBankparser:
    
    def __init__(self, dbhost, dbuser, dbpasswd, database):
        self.mt = dt.tables(dbhost, dbuser, dbpasswd, database)
        self.mq = dq.query(dbhost, dbuser, dbpasswd, database)
        #table information
        self.tableDescription = '''DB_card VARCHAR(40), DrugBrand_Name VARCHAR(200), CAS_Registry_Number VARCHAR(100), Generic_name VARCHAR(200), Target_geneName VARCHAR(40), Target_PDBID VARCHAR(40),
                                 Target_name VARCHAR(100), INDEX tg_namepA (Target_geneName), INDEX dg_name (CAS_Registry_Number), INDEX dbcard (DB_card)'''
        self.tableName = 'DrugBank_db_2'
    
    
    def parse_drugBankdb(self, inputfile, outputfile):
        """
        It reads a file of drugBank cards
        """
        # other labels to consider: # Drug_Type:
        # Note: just realize It can be more than one target by drug in hte same record. Each is distinguish by the _#_ It seems it is always the 3 record in a list of items separated by _
        #dbcards = {}
        dbcards=defaultdict(list)
        
        tags = set(['#BEGIN_DRUGCARD', 'Brand_Names:','CAS_Registry_Number:','Generic_Name:','Drug_Target_1_Gene_Name:','Drug_Target_1_PDB_ID:','Drug_Target_1_Name:',])
        next_line_has_value = False
        key=''

        drugs_list=deque([])
             
        for line in inputfile:        
            line = line.strip('\n')
            
            if line == '': 
                continue
            
            # you previously detected a key that you want
            # so get its value         
            if next_line_has_value:
                value = line.split('\t')
                dbcards[key].append(value) 
                next_line_has_value = False
                continue

            # check to see if this is a key that you want
            if line.startswith('#'):
                #next_line_has_value = False
                subfield = line.split(' ')
                
                if subfield[0]=='#END_DRUGCARD':
                    #print dbcards
                    
                    #check for missing keys and values
                    thisdbtags = dbcards.keys()
                    missing_tags=tags.difference(thisdbtags)
                    
                    for k in missing_tags:
                        dbcards[k].append(['Not Available'])
                    
                    
                    drugs_list.append( drugBankrecord2(dbcards) )
                    dbcards=defaultdict(list)
                    
                
                if  subfield[0]=='#BEGIN_DRUGCARD':
                    key=subfield[0]
                    dbcards[key].append([subfield[1]])
                    continue
                # check the key
                key = subfield[1]
                if key in tags:
                    next_line_has_value=True
                    continue
     
        # Output the a file for creating the database
        for thisdrug in drugs_list:
            outline = sum(thisdrug.print_myvalues(),[])
            outputfile.write(",".join( outline ).replace(',','\t')+'\n')
                
    
    def create_drugBank_db(self, folderpath):
        """
        It creates a databases of p2p interactions using the files provided in the folderpath.
        """
        self.mt.create_connector()
        dbfiles=[]
        for infile in glob.glob( os.path.join(folderpath, '*.db') ):
            dbfiles.append(infile)

        for dbf in dbfiles:     
            if not(self.mt.table_existence(self.tableName)):
                self.mt.create_table(self.tableName,self.tableDescription)
                
            self.mt.load_data_table(self.tableName,dbf)
            
    
    def get_drungBank_targets(self,genelist):
        
        #create a dictionary with key gen, value drugs that target the gene
        # Query the database
        # return the drug dictionary.
        self.mq.create_connector()
        drugDict={}
        for g in genelist:
            drugDict[g]=[]
         
        drugDict =  self.mq.get_drugTargetslist(genelist,drugDict,self.tableName)    
        
        return drugDict
            
            
            
        

             

''' 
inputfile=open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/drugcards.txt")
outputfile=open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/drugcards.db",'w')
tp = pm.parser()
db = drugBankparser("localhost", "oabalbin", "oscar", "signatures")
#db.parse_drugBankdb(inputfile, outputfile)
#db.create_drugBank_db("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/")
#genelist=['ERG','PRKDC','PARP1','DDX5','AR','NUMA1','PRPF8','TOP2B','XRCC5','ABL1','ACP5','ACTL6A']
genelist=tp.list_of_names(open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/factor_genesTest.txt"))
outfile = open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/factor_drugTargets.txt",'w')
print genelist
drugDict = db.get_drungBank_targets(list(set(genelist)))

outfile=open("/home/oabalbin/projects/networks/compounds_DB/DrugBankdb/drugs_targets.txt",'w')

for g,druglist in drugDict.iteritems():
    for genrecord in druglist:
        outline =[genrecord.targetGen, genrecord.targetProt, genrecord.dbcard, genrecord.genericname, genrecord.brandname, genrecord.casRegistry]
        print outline
        outfile.write(",".join(outline).replace(',','\t')+'\n')

'''

